---
import Icon from "../components/misc/Icon.astro";
import IconifyLoader from "../components/misc/IconifyLoader.astro";
import {
	getCurrentItems,
	getFeaturedTimeline,
	getTimelineByType,
	getTimelineStats,
	getTotalWorkExperience,
	timelineData,
} from "../data/timeline";
import I18nKey from "../i18n/i18nKey";
import { i18n } from "../i18n/translation";
import MainGridLayout from "../layouts/MainGridLayout.astro";

export const prerender = true;
const { lang } = Astro.props;

// 收集所有时间线图标用于预加载
const allIcons = timelineData
	.map((item) => item.icon || getTypeIcon(item.type))
	.filter(Boolean);

// 获取时间线统计信息
const stats = getTimelineStats();
const featuredItems = getFeaturedTimeline();
const currentItems = getCurrentItems();
const workExperience = getTotalWorkExperience();

// 获取所有时间线项目（按时间倒序）
const allTimelineItems = getTimelineByType();

// 类型图标映射
const getTypeIcon = (type: string) => {
	switch (type) {
		case "education":
			return "material-symbols:school";
		case "work":
			return "material-symbols:work";
		case "project":
			return "material-symbols:code";
		case "achievement":
			return "material-symbols:emoji-events";
		default:
			return "material-symbols:event";
	}
};

// 格式化日期
const formatDate = (dateString: string) => {
	const date = new Date(dateString);
	return date.toLocaleDateString("zh-CN", { year: "numeric", month: "long" });
};

// 计算持续时间
const getDuration = (startDate: string, endDate?: string) => {
	const start = new Date(startDate);
	const end = endDate ? new Date(endDate) : new Date();
	const diffTime = Math.abs(end.getTime() - start.getTime());
	const diffMonths = Math.ceil(diffTime / (1000 * 60 * 60 * 24 * 30));

	if (diffMonths < 12) {
		return `${diffMonths} ${i18n(I18nKey.timelineMonths)}`;
	}
	const years = Math.floor(diffMonths / 12);
	const months = diffMonths % 12;
	if (months === 0) {
		return `${years} ${i18n(I18nKey.timelineYears)}`;
	}
	return `${years} ${i18n(I18nKey.timelineYears)} ${months} ${i18n(I18nKey.timelineMonths)}`;
};

const title = i18n(I18nKey.timeline);
const subtitle = i18n(I18nKey.timelineSubtitle);
---

<MainGridLayout title={title} description={subtitle}>
  <!-- 图标加载器，预加载所有时间线图标 -->
  <IconifyLoader preloadIcons={allIcons} />
  <div class="flex w-full rounded-[var(--radius-large)] overflow-hidden relative min-h-32">
    <div class="card-base z-10 px-9 py-6 relative w-full">
      <!-- 页面标题 -->
      <div class="flex flex-col items-start justify-center mb-8">
        <h1 class="text-4xl font-bold text-black/90 dark:text-white/90 mb-2">
          {i18n(I18nKey.timeline)}
        </h1>
        <p class="text-lg text-black/60 dark:text-white/60">
          {i18n(I18nKey.timelineSubtitle)}
        </p>
      </div>

      <!-- 统计信息 -->
      <div class="grid grid-cols-1 md:grid-cols-4 gap-4 mb-8">
        <div class="bg-gradient-to-br from-blue-50 to-blue-100 dark:from-blue-900/20 dark:to-blue-800/20 rounded-lg p-4">
          <div class="text-2xl font-bold text-blue-600 dark:text-blue-400">{stats.total}</div>
          <div class="text-sm text-blue-600/70 dark:text-blue-400/70">{i18n(I18nKey.timelineTotal)}</div>
        </div>
        <div class="bg-gradient-to-br from-green-50 to-green-100 dark:from-green-900/20 dark:to-green-800/20 rounded-lg p-4">
          <div class="text-2xl font-bold text-green-600 dark:text-green-400">{stats.byType.work}</div>
          <div class="text-sm text-green-600/70 dark:text-green-400/70">{i18n(I18nKey.timelineWork)}</div>
        </div>
        <div class="bg-gradient-to-br from-purple-50 to-purple-100 dark:from-purple-900/20 dark:to-purple-800/20 rounded-lg p-4">
          <div class="text-2xl font-bold text-purple-600 dark:text-purple-400">{stats.byType.project}</div>
          <div class="text-sm text-purple-600/70 dark:text-purple-400/70">{i18n(I18nKey.timelineProjects)}</div>
        </div>
        <div class="bg-gradient-to-br from-orange-50 to-orange-100 dark:from-orange-900/20 dark:to-orange-800/20 rounded-lg p-4">
          <div class="text-2xl font-bold text-orange-600 dark:text-orange-400">
            {workExperience.years}+
          </div>
          <div class="text-sm text-orange-600/70 dark:text-orange-400/70">{i18n(I18nKey.timelineExperience)}</div>
        </div>
      </div>

      <!-- 当前进行中的项目 -->
      {currentItems.length > 0 && (
        <div class="mb-8">
          <h2 class="text-2xl font-bold text-black/90 dark:text-white/90 mb-4">
            {i18n(I18nKey.timelineCurrent)}
          </h2>
          <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            {currentItems.map((item) => (
              <div class="bg-white dark:bg-gray-800 rounded-lg border border-black/10 dark:border-white/10 p-6 hover:shadow-lg transition-shadow duration-300">
                <div class="flex items-start gap-4">
                  <div class="w-12 h-12 rounded-lg flex items-center justify-center" style={`background-color: ${item.color || 'rgb(99 102 241)'}20`}>
                    <Icon 
                      icon={item.icon || getTypeIcon(item.type)} 
                      class="text-2xl" 
                      color={item.color || 'rgb(99 102 241)'}
                      fallback={item.title.charAt(0)}
                      loading="eager"
                    />
                  </div>
                  <div class="flex-1">
                    <div class="flex items-start justify-between mb-2">
                      <h3 class="text-xl font-semibold text-black/90 dark:text-white/90">
                        {item.title}
                      </h3>
                      <span class="px-2 py-1 text-xs bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400 rounded-full">
                        {i18n(I18nKey.timelineCurrent)}
                      </span>
                    </div>
                    {item.organization && (
                      <div class="text-sm text-black/70 dark:text-white/70 mb-1">
                        {item.organization} {item.position && `• ${item.position}`}
                      </div>
                    )}
                    {item.location && (
                      <div class="text-sm text-black/60 dark:text-white/60 mb-2">
                        📍 {item.location}
                      </div>
                    )}
                    <p class="text-black/60 dark:text-white/60 mb-3 text-sm">
                      {item.description}
                    </p>
                    <div class="text-sm text-black/70 dark:text-white/70 mb-3">
                      {formatDate(item.startDate)} - {i18n(I18nKey.timelinePresent)} ({getDuration(item.startDate)})
                    </div>
                    {item.skills && item.skills.length > 0 && (
                      <div class="flex flex-wrap gap-1 mb-3">
                        {item.skills.map((skill) => (
                          <span class="px-2 py-1 text-xs bg-indigo-100 text-indigo-700 dark:bg-indigo-900/30 dark:text-indigo-400 rounded">
                            {skill}
                          </span>
                        ))}
                      </div>
                    )}
                    {item.links && item.links.length > 0 && (
                      <div class="flex gap-3">
                        {item.links.map((link) => (
                          <a 
                            href={link.url} 
                            target="_blank" 
                            rel="noopener noreferrer"
                            class="text-indigo-600 dark:text-indigo-400 hover:underline text-sm font-medium"
                          >
                            {link.name}
                          </a>
                        ))}
                      </div>
                    )}
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      <!-- 时间线 -->
      <div class="mb-8">
        <h2 class="text-2xl font-bold text-black/90 dark:text-white/90 mb-6">
          {i18n(I18nKey.timelineHistory)}
        </h2>
        <div class="relative">
          <!-- 时间线主轴 -->
          <div class="absolute left-6 top-0 bottom-0 w-0.5 bg-gray-200 dark:bg-gray-700"></div>
          
          <div class="space-y-8">
            {allTimelineItems.map((item, index) => (
              <div class="relative flex items-start gap-6">
                <!-- 时间线节点 -->
                <div class="relative z-10 w-12 h-12 rounded-full flex items-center justify-center" style={`background-color: ${item.color || 'rgb(99 102 241)'}`}>
                  <Icon 
                    icon={item.icon || getTypeIcon(item.type)} 
                    class="text-xl text-white" 
                    color="white"
                    fallback={item.title.charAt(0)}
                    loading="eager"
                  />
                </div>
                
                <!-- 内容卡片 -->
                <div class="flex-1 bg-white dark:bg-gray-800 rounded-lg border border-black/10 dark:border-white/10 p-6 hover:shadow-lg transition-shadow duration-300">
                  <div class="flex items-start justify-between mb-3">
                    <div>
                      <h3 class="text-xl font-semibold text-black/90 dark:text-white/90 mb-1">
                        {item.title}
                      </h3>
                      {item.organization && (
                        <div class="text-sm text-black/70 dark:text-white/70">
                          {item.organization} {item.position && `• ${item.position}`}
                        </div>
                      )}
                    </div>
                    <span class={`px-2 py-1 text-xs rounded-full ${
                      item.type === 'education' ? 'bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400' :
                      item.type === 'work' ? 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400' :
                      item.type === 'project' ? 'bg-purple-100 text-purple-700 dark:bg-purple-900/30 dark:text-purple-400' :
                      'bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-400'
                    }`}>
                      {i18n(item.type === 'education' ? I18nKey.timelineEducation :
                            item.type === 'work' ? I18nKey.timelineWork :
                            item.type === 'project' ? I18nKey.timelineProject :
                            I18nKey.timelineAchievement)}
                    </span>
                  </div>
                  
                  <div class="flex items-center gap-4 mb-3 text-sm text-black/60 dark:text-white/60">
                    <div>
                      {formatDate(item.startDate)} - {item.endDate ? formatDate(item.endDate) : i18n(I18nKey.timelinePresent)}
                    </div>
                    <div>•</div>
                    <div>{getDuration(item.startDate, item.endDate)}</div>
                    {item.location && (
                      <>
                        <div>•</div>
                        <div>📍 {item.location}</div>
                      </>
                    )}
                  </div>
                  
                  <p class="text-black/70 dark:text-white/70 mb-4">
                    {item.description}
                  </p>
                  
                  {item.achievements && item.achievements.length > 0 && (
                    <div class="mb-4">
                      <h4 class="text-sm font-semibold text-black/80 dark:text-white/80 mb-2">
                        {i18n(I18nKey.timelineAchievements)}
                      </h4>
                      <ul class="space-y-1">
                        {item.achievements.map((achievement) => (
                          <li class="text-sm text-black/70 dark:text-white/70 flex items-start gap-2">
                            <span class="text-green-500 mt-1">•</span>
                            <span>{achievement}</span>
                          </li>
                        ))}
                      </ul>
                    </div>
                  )}
                  
                  {item.skills && item.skills.length > 0 && (
                    <div class="mb-4">
                      <div class="flex flex-wrap gap-1">
                        {item.skills.map((skill) => (
                          <span class="px-2 py-1 text-xs bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-300 rounded">
                            {skill}
                          </span>
                        ))}
                      </div>
                    </div>
                  )}
                  
                  {item.links && item.links.length > 0 && (
                    <div class="flex gap-4">
                      {item.links.map((link) => (
                        <a 
                          href={link.url} 
                          target="_blank" 
                          rel="noopener noreferrer"
                          class="text-blue-600 dark:text-blue-400 hover:underline text-sm font-medium flex items-center gap-1"
                        >
                          {link.type === 'certificate' && '🏆'}
                          {link.type === 'project' && '🔗'}
                          {link.type === 'website' && '🌐'}
                          {link.name}
                        </a>
                      ))}
                    </div>
                  )}
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>

      <!-- 类型统计 -->
      <div class="mt-12 pt-8 border-t border-black/10 dark:border-white/10">
        <h2 class="text-2xl font-bold text-black/90 dark:text-white/90 mb-6">
          {i18n(I18nKey.timelineStatistics)}
        </h2>
        <div class="grid grid-cols-1 md:grid-cols-2 gap-8">
          <!-- 按类型分布 -->
          <div>
            <h3 class="text-lg font-semibold text-black/80 dark:text-white/80 mb-4">
              {i18n(I18nKey.timelineByType)}
            </h3>
            <div class="space-y-3">
              {Object.entries(stats.byType).map(([type, count]) => {
                const percentage = Math.round((count / stats.total) * 100);
                return (
                  <div class="flex items-center gap-3">
                    <div class="w-20 text-sm text-black/70 dark:text-white/70">
                      {i18n(type === 'education' ? I18nKey.timelineEducation :
                            type === 'work' ? I18nKey.timelineWork :
                            type === 'project' ? I18nKey.timelineProject :
                            I18nKey.timelineAchievement)}
                    </div>
                    <div class="flex-1 bg-gray-200 dark:bg-gray-700 rounded-full h-2">
                      <div 
                        class={`h-2 rounded-full transition-all duration-500 ${
                          type === 'education' ? 'bg-blue-500' :
                          type === 'work' ? 'bg-green-500' :
                          type === 'project' ? 'bg-purple-500' :
                          'bg-orange-500'
                        }`}
                        style={`width: ${percentage}%`}
                      ></div>
                    </div>
                    <div class="w-12 text-sm text-black/70 dark:text-white/70 text-right">
                      {count}
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
          
          <!-- 工作经验详情 -->
          <div>
            <h3 class="text-lg font-semibold text-black/80 dark:text-white/80 mb-4">
              {i18n(I18nKey.timelineWorkExperience)}
            </h3>
            <div class="space-y-3">
              <div class="flex justify-between items-center">
                <span class="text-black/70 dark:text-white/70">{i18n(I18nKey.timelineTotalExperience)}</span>
                <span class="font-semibold text-black/90 dark:text-white/90">
                  {workExperience.years} {i18n(I18nKey.timelineYears)} {workExperience.months} {i18n(I18nKey.timelineMonths)}
                </span>
              </div>
              <div class="flex justify-between items-center">
                <span class="text-black/70 dark:text-white/70">{i18n(I18nKey.timelineWorkPositions)}</span>
                <span class="font-semibold text-black/90 dark:text-white/90">{stats.byType.work}</span>
              </div>
              <div class="flex justify-between items-center">
                <span class="text-black/70 dark:text-white/70">{i18n(I18nKey.timelineCurrentRole)}</span>
                <span class="font-semibold text-black/90 dark:text-white/90">
                  {currentItems.filter(item => item.type === 'work').length > 0 ? i18n(I18nKey.timelineEmployed) : i18n(I18nKey.timelineAvailable)}
                </span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</MainGridLayout>

<style>
  .line-clamp-2 {
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
  }
</style>

<script>
  // 确保图标库已加载，并处理页面导航
  document.addEventListener('DOMContentLoaded', () => {
    // 如果图标加载器存在，确保图标已加载
    if (window.__iconifyLoader) {
      window.__iconifyLoader.load().then(() => {
        // 图标加载完成后，触发时间线项目的重新渲染
        const timelineItems = document.querySelectorAll('.timeline-item');
        timelineItems.forEach(item => {
          item.dispatchEvent(new CustomEvent('iconify-ready'));
        });
      }).catch(error => {
        console.error('Failed to load icons on timeline page:', error);
      });
    }
  });

  // 处理页面导航时的图标重新加载
  if (typeof window !== 'undefined') {
    // 监听页面显示事件（包括前进/后退导航）
    window.addEventListener('pageshow', (event) => {
      if (event.persisted && window.__iconifyLoader) {
        // 页面从缓存恢复，重新检查图标状态
        setTimeout(() => {
          window.__iconifyLoader.load().catch(console.error);
        }, 100);
      }
    });
  }
</script>